package ai.moran.demo.es;

import ai.moran.demo.utils.DateTimeUtils;
import ai.moran.demo.common.es.EsJestService;
import ai.moran.demo.utils.LogUtility;
import ai.moran.demo.common.es.ScrollSearchPageResult;


import io.searchbox.core.search.sort.Sort;
import lombok.Data;


import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static junit.framework.TestCase.assertNotNull;
import static junit.framework.TestCase.assertTrue;


public class TestScrollSearch {

    private static final Logger logger = LoggerFactory.getLogger(TestScrollSearch.class);

    @Data
    public static class EsOrderDetail {
        private Integer status;
        private String statusName;
        private String createTime;
        private String key;
        private Integer statusGroup;
        private String statusGroupName;
        private String modifiedTime;
        private Integer product2BackFlowOffset;
        private String orderCode;
        private String detail;
        private String summary;

    }

    private static EsJestService esJestService;
    private static String indexName;
    private static String indexType;
    private static Integer scrollSize;
    private static String scrollTime;

    @BeforeClass
    public static void init() {
        esJestService = new EsJestService.Builder("39.105.156.215", "9200").build();
        indexName = "sale";
        indexType = "orders";
        scrollSize = 500;
        scrollTime = "5m";
    }
    @Test
    public void testScrollSearchPaging() {
        try {
            BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

            boolQueryBuilder.must(QueryBuilders.rangeQuery("createTime")
                    .lt(DateTimeUtils.getTimeString(DateTimeUtils.getDayFromMidNight(1),
                            DateTimeUtils.FORMAT_DEFAULT))
                    .gt(DateTimeUtils.getTimeString(DateTimeUtils.getDayFromMidNight(-30),
                            DateTimeUtils.FORMAT_DEFAULT)));

            boolQueryBuilder.must(QueryBuilders.termQuery("key", "8611BDBE67BD3C1A"));

            int pageSize = 100, current = 11;
            Sort sort = new Sort("createTime", Sort.Sorting.ASC);
            ScrollSearchPageResult<EsOrderDetail> orderDetailPageResult
                    = esJestService.pageScrollSearch(indexName, indexType, pageSize, current, EsOrderDetail.class,
                    null, sort, boolQueryBuilder);

            assertNotNull(orderDetailPageResult);

        } catch (Exception e) {
            LogUtility.logException(logger, e);
            assertTrue(false);
        }
    }


}